package com.woniu.park.controller;

/**
 * @version: V1.0
 * @author: 陈小宝
 * @className: ExceptionController
 * @packageName: com.woniu.all.controller
 * @description: 全局异常处理
 * @data: 2020-09-03 19:25
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 将所有controller视作一个切面，提供一些功能
 * 比如全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionController {


    /**
     * 描述：捕获Exception 异常
     * @param model 将Model对象注入到方法中
     * @param e 将产生异常对象注入到方法中
     * @return 指定错误页面
     */
    @ExceptionHandler(value = {ArithmeticException.class})
    public String arithmeticExceptionHandle(Model model, Exception e) {

        model.addAttribute("msg", "数学运算异常:" + e.getMessage());
        log.info(e.getMessage());
        return "error";
    }

    @ExceptionHandler(value = {NullPointerException.class})
    public String nullPointerException(Model model, Exception e) {

        model.addAttribute("msg", "空指针异常:" + e.getMessage());
        log.info(e.getMessage());

        return "error";
    }

    @ExceptionHandler(value = {RuntimeException.class})
    public String runtimeException(Model model, Exception e) {

        model.addAttribute("msg", "全局捕获异常:" + e.getMessage());
        log.info("运行时异常"+e.getStackTrace()+e.getCause()+e.getMessage());
        return "error";
    }

}